<template>
    <el-main>
      <!-- 顶部操作区 -->
      <el-form :inline="true">
        <el-form-item label="客户姓名">
          <el-input v-model="filters.clientName" placeholder="请输入客户姓名" clearable @keyup.enter="onSearch" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="success" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" style="width: 100%">
        <el-table-column type="index" label="序号" width = "80" />
        <el-table-column prop="clientName" label="客户姓名" />
        <el-table-column prop="outReason" label="外出原因" show-overflow-tooltip />
        <el-table-column prop="outTime" label="外出时间" :formatter="formatDateTime" />
        <el-table-column prop="expectReturnTime" label="预计返回时间" :formatter="formatDateTime" />

        <el-table-column prop="returnTime" label="实际返回时间" >
          <template #default="scope">
            <span v-if="scope.row.returnTime">{{ formatDateTime(scope.row, null, scope.row.returnTime) }}</span>
            <span v-else>---</span>
          </template>
        </el-table-column>

        <el-table-column prop="outReviewStatus" label="审核状态">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.outReviewStatus)">
              {{ scope.row.outReviewStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="outReviewTime" label="审核时间" :formatter="formatDateTime" />


        <el-table-column label="操作">
          <template #default="scope">
            <el-button
                v-if="userRole === '管理员'"
                type="warning"
                @click="openAuditDialog(scope.row)"
                :disabled="scope.row.outReviewStatus !== '已提交'"
            >
              审核
            </el-button>


            <el-button
                v-if="userRole === '健康管家' "
                type="success"
                @click="openReturnDialog(scope.row)"
                :disabled="scope.row.outReviewStatus !== '通过' || scope.row.returnTime"
            >
              登记返回
            </el-button>
          </template>
        </el-table-column>


      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" style="margin-top: 20px; display: flex; justify-content: flex-end;">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[6, 10, 20, 50]"
            @current-change="handlePageChange"
            @size-change="handleSizeChange">
        </el-pagination>
      </div>

      <!-- 用于登记返回时间的对话框 -->
      <el-dialog v-model="returnDialog.visible" title="登记客户返回时间" width="400px">
        <el-form label-width="110px">
          <el-form-item label="客户姓名">
            <el-input :value="returnDialog.clientName" disabled />
          </el-form-item>
          <el-form-item label="实际返回时间">
            <el-date-picker
                v-model="returnDialog.time"
                type="datetime"
                placeholder="请选择返回时间"
                style="width: 100%;"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="returnDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitReturnTime" :loading="returnDialog.loading">确认</el-button>
        </template>
      </el-dialog>

      <!-- 审核对话框 (系统管理员使用) -->
      <el-dialog v-model="auditDialog.visible" title="外出申请审核" width="500px">
        <el-form ref="auditFormRef" :model="auditForm.data" :rules="auditForm.rules" label-width="100px">
          <el-form-item label="审核结果" prop="outReviewStatus">
            <el-radio-group v-model="auditForm.data.outReviewStatus">
              <el-radio :value="'通过'">通过</el-radio>
              <el-radio :value="'不通过'">不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核意见" prop="outDescription">
            <el-input v-model="auditForm.data.outDescription" type="textarea" :rows="3" placeholder="若不通过，请填写原因" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="auditDialog.visible=false">取消</el-button>
          <el-button type="primary" @click="submitAudit" :loading="auditDialog.loading">确认审核</el-button>
        </template>
      </el-dialog>
    </el-main>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { applyForOuting, listOutRequests, auditRequest, recordClientReturn } from '@/api/apiList/outing.js';

// --- 接收传入的角色和ID ---
const userRole = ref(localStorage.getItem('role'));
const userId = ref(localStorage.getItem('adminId'));
const numericUserId = userId.value ? parseInt(userId.value, 10) : null;

// --- 通用状态 ---
const loading = ref(false);
const tableData = ref([]);
const filters = reactive({ clientName: '' });
const pagination = reactive({ total: 0, currentPage: 1, pageSize: 6 });

// --- 审核表单状态 ---
const auditDialog = reactive({ visible: false, loading: false });
const auditFormRef = ref(null);
const currentRecordId = ref(null);
const getInitialAuditForm = () => ({ outReviewStatus: '通过', outDescription: '同意。' });
const auditForm = reactive({
  data: getInitialAuditForm(),
  rules: {
    outReviewStatus: [{ required: true, message: '请选择审核结果' }],
  }
});

// 新增登记返回对话框的状态
const returnDialog = reactive({
  visible: false,
  loading: false,
  outingId: null,
  clientName: '',
  time: null,
});

// --- 方法 ---
async function fetchData() {
  loading.value = true;
  try {
    const query = { clientName: filters.clientName };
    console.log(userRole.value,userId.value);
    if (userRole.value === '健康管家') {
      query.adId = numericUserId;
    }
    const params = { pageNum: pagination.currentPage, pageSize: pagination.pageSize, query };
    const pageData = await listOutRequests(params);
    tableData.value = pageData.records;
    pagination.total = pageData.total;
  } catch (error) { console.error("获取列表失败:", error); }
  finally { loading.value = false; }
}
function handlePageChange(newPage) {
  pagination.currentPage = newPage;
  fetchData();
}

function handleSizeChange(newSize) {
  pagination.pageSize = newSize;
  pagination.currentPage = 1;
  fetchData();
}
const getStatusTag = (s) => {
  const tagMap = {
    '已提交': 'primary',
    '通过': 'success',
    '不通过': 'danger'
  };
  return tagMap[s] || 'info'; // 如果状态未知，返回灰色标签
};
const onSearch = () => { pagination.currentPage = 1; fetchData(); };
const onReset = () => {filters.clientName = ''; onSearch();};

const formatDateTime = (row, column, cellValue) => {
  if (!cellValue) {
    return '';
  }
  try {
    const date = new Date(cellValue);
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return '无效日期';
    }
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    return '格式化错误';
  }
};

function openAuditDialog(row) {
  currentRecordId.value = row.outId;
  Object.assign(auditForm.data, getInitialAuditForm());
  if (auditFormRef.value) auditFormRef.value.clearValidate();
  auditDialog.visible = true;
}

function submitAudit() {
  if (!auditFormRef.value) return;
  auditFormRef.value.validate(async (valid) => {
    if(!valid) return;
    auditDialog.loading = true;
    try {
      const auditData = {
        outId: currentRecordId.value,         // 必需：要更新哪条记录
        adId: numericUserId,                        // 必需：审核人是谁
        outReviewStatus: auditForm.data.outReviewStatus,
        outDescription: auditForm.data.outDescription
      };
      // 2. 调用API，传入组装好的对象
      await auditRequest(auditData);
      ElMessage.success('审核操作成功');
      auditDialog.visible = false;
      fetchData();
    } catch(e) {
      console.error("审核失败:", e);
    }
    finally {
      auditDialog.loading = false;
    }
  });
}

// 新增打开登记返回对话框的方法
const openReturnDialog = (row) => {
  returnDialog.outingId = row.outId;
  returnDialog.clientName = row.clientName;
  returnDialog.time = new Date(); // 默认填充当前时间
  returnDialog.visible = true;
};

// 新增提交返回时间的方法
const submitReturnTime = async () => {
  if (!returnDialog.time) {
    ElMessage.warning('请选择实际返回时间');
    return;
  }

  returnDialog.loading = true;
  try {
    await recordClientReturn(returnDialog.outingId, returnDialog.time);
    ElMessage.success('登记成功，床位状态已更新！');
    returnDialog.visible = false;
    fetchData(); // 成功后刷新列表
  } catch (error) {
    console.error("登记返回时间失败:", error);
  } finally {
    returnDialog.loading = false;
  }
};


onMounted(fetchData);

</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.outing-return-time-popper {
  z-index: 3000 !important; /* !important 用于确保覆盖Element Plus的默认样式 */
}
</style>
